package com.example.nbshangpping.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.nbshangpping.MainActivity;
import com.example.nbshangpping.login.UserBean;
// 用户登录成功之后，保存到本地的工具类
// 1.共享参数文件保存    2file存储     3.数据库存储
public class SaveUserUtils {
    private static UserBean.DataBean dataBean = null;
    // 将用户个人信息保存到内存当中
    public static boolean saveUserToMemory(UserBean.DataBean bean){
        dataBean = bean;
        return true;
    }
    // 将用户登录的个人信息保存到文件
    public static boolean saveUserToFile(Context context, UserBean.DataBean data){
        //共享参数保存数据的步骤
        // 1.获取共享参数对象
        SharedPreferences pref = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        // 2.获取编辑对象
        SharedPreferences.Editor editor = pref.edit();
        //3.开始写入数据
        editor.putInt("id",data.getId());
        editor.putString("phone",data.getPhone());
        editor.putString("password",data.getPassword());
        editor.putString("name",data.getName());
        editor.putString("address",data.getAddress());
        editor.putString("nickname",data.getNickname());
        editor.putString("question",data.getQuestion());
        editor.putString("answer",data.getAnswer());
        //4.提交结果
        editor.commit();
        //保存到内存中
        saveUserToMemory(data);
        return true;
    }

    // 从文件获取用户信息数据
    public static UserBean.DataBean getUserFromFile(Context context){
//        1.获取共享参数对象
        SharedPreferences pref = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        int id = pref.getInt("id", -1);
        String phone = pref.getString("phone", "");
        String password = pref.getString("password", "");
        String name = pref.getString("name", "");
        String address = pref.getString("address", "");
        String nickname = pref.getString("nickname", "");
        String question = pref.getString("question", "");
        String answer = pref.getString("answer", "");
        UserBean.DataBean bean = new UserBean.DataBean();
        bean.setId(id);
        bean.setPhone(phone);
        bean.setName(name);
        bean.setPassword(password);
        bean.setAnswer(answer);
        bean.setQuestion(question);
        bean.setNickname(nickname);
        bean.setAddress(address);
        return bean;
    }
    //    获取用户信息：先从内存获取，如果内存没有，从文件获取
    public static UserBean.DataBean getUserInfo(Context context){
        if (dataBean!=null) {
            return dataBean;
        }
        UserBean.DataBean user = getUserFromFile(context);
        if (user.getId()!=-1) {
            dataBean = user;
            return dataBean;
        }
        return null;
    }
//删除用户信息
    public static void deleteUserInfo(Context context) {
        SharedPreferences pref = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();
        editor.commit();
        dataBean = null;
    }
}